/**
 *    Copyright 2009-2020 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.aapl.interceptor;

import org.apache.ibatis.aapl.annotation.EnhanceEarlyField;
import org.apache.ibatis.aapl.annotation.strategy.EnhanceEarlyFieldStrategy;
import org.apache.ibatis.aapl.reflect.MetaUtils;
import org.apache.ibatis.aapl.registry.MethodRegistry;
import org.apache.ibatis.aapl.registry.SqlMethod;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.scripting.defaults.DefaultParameterHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author gu
 * @date 2020/4/7 11:12
 */
public class EnhanceEarlyFieldProcessor implements ParameterProcessor {

  public static final Logger log = LoggerFactory.getLogger(EnhanceEarlyFieldProcessor.class);

  private MethodRegistry registry = MethodRegistry.getMethodRegistry();

  private Map<Class<? extends EnhanceEarlyFieldStrategy>, EnhanceEarlyFieldStrategy> strategyMap = new HashMap<>(32);

  @Override
  public void process(ParameterHandler handler) {
    Object object = handler.getParameterObject();
    if (object == null) {
      return;
    }
    doProcess(object, handler);
  }

  private void doProcess(Object object, ParameterHandler handler) {
    if (!(handler instanceof DefaultParameterHandler)) {
      return;
    }
    SqlMethod method = registry.getMethod(((DefaultParameterHandler) handler));
    EnhanceEarlyField annotation = method.getMethod().getAnnotation(EnhanceEarlyField.class);
    if (annotation == null) {
      return;
    }
    String[] fields = annotation.fields();
    if (fields.length == 0) {
      return;
    }
    Class<? extends EnhanceEarlyFieldStrategy>[] strategies = annotation.strategies();
    if (fields.length != strategies.length) {
      log.error("要增强的字段长度({})和对应的策略长度({})不一致！", fields.length, strategies.length);
      return;
    }
    for (int i = 0; i < fields.length; i++) {
      String field = fields[i];
      Class<? extends EnhanceEarlyFieldStrategy> strategy = strategies[i];
      EnhanceEarlyFieldStrategy enhanceEarlyFieldStrategy = strategyMap.computeIfAbsent(strategy, k -> {
        try {
          return strategy.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
          log.warn("请确保 {} 存在public且参数为空的构造函数！", strategy);
          return null;
        }
      });
      MetaObject metaObject = MetaUtils.getMetaObject(object);
      Object value = metaObject.getValue(field);
      metaObject.setValue(field, enhanceEarlyFieldStrategy.enhance(value));
    }
  }
}
